package edu.towson.cis.cosc490.jpanne.npr.main;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import edu.towson.cis.cosc490.jpanne.npr.R;
import edu.towson.cis.cosc490.jpanne.npr.data.NPRData;
import edu.towson.cis.cosc490.jpanne.npr.parsers.AndroidSaxFeedParser;
import static edu.towson.cis.cosc490.jpanne.npr.data.Constants.SAVED;

public class NPRMainActivity extends ListActivity {
	
	private List<NPRItem> nprList;
	private NPRData nprData;
	private boolean serviceFlag;
	AlarmManager alarms;
	private String feedURL = "http://www.npr.org/rss/rss.php?id=1001";
	private final String debug = "Debug";
	private int position;
    
	@Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.main);
        nprData = new NPRData(this);
        loadFeed();
        Log.i(debug, "loadFeed() done");
        setAlarm();  
        Log.i(debug, "setAlarm() done");
        startService(new Intent(NPRMainActivity.this, NPRMusicService.class));
        Log.i(debug, "startService() done");
        registerForContextMenu(getListView());
    } 
	
	
	public void onPause(){
		super.onPause();
		stopService(new Intent(NPRMainActivity.this, NPRMusicService.class));
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		//Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(nprList.get(position).getLink().toExternalForm()));
		//startActivity(viewMessage);
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	menu.setHeaderTitle("Select an action");
    	menu.add(1, v.getId(), 0, "Open Article");
    	menu.add(2, v.getId(), 1, "Email Article");
    	menu.add(3, v.getId(), 2, "Save Article");
    	menu.add(4, v.getId(), 3, "Tweet Article");
    }
	
	 public boolean onContextItemSelected(MenuItem item) {
		 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		 position = info.position;
		 if(item.getTitle() == "Open Article"){
			 Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(nprList.get(position).getLink().toExternalForm()));
			 startActivity(viewMessage);
		 } else if(item.getTitle()== "Email Article"){
			 Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			 emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Look what I found on NPR!");
			 emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hey, check this out! \n\n" 
					 + nprList.get(position).getDescription() + "\n\n" +  nprList.get(position).getLink());
		     emailIntent.setType("plain/text");
		     startActivity(Intent.createChooser(emailIntent, "Send email..."));
		 } else if(item.getTitle()== "Save Article"){
			 //SAVE DATA
			 String savedArticleTitle = nprList.get(position).getTitle();
			 try{
				 SQLiteDatabase db = nprData.getWritableDatabase();
				 ContentValues values = new ContentValues();
				 values.put(SAVED, "1");
				 int result = db.update("Npr", values, "title=?", new String[]{savedArticleTitle});
				 Log.i("sql", ""+result);
				 //db.rawQuery("UPDATE Npr SET " + SAVED +"=? WHERE " + TITLE +"=?", new String[]{"1", savedArticleTitle});
			 }catch(Exception e){e.printStackTrace();}			 

		 }else if(item.getTitle()== "Tweet Article"){
			 String tweetText = nprList.get(position).getTitle();
			 Intent tweet = new Intent(Intent.ACTION_VIEW);
			 tweet.setAction("android.intent.action.SEND");
			 tweet.setFlags(0x3000000);
			 tweet.setType("text/plain");
			 tweet.setClassName("com.twitter.android", "com.twitter.android.PostActivity");
			 tweet.putExtra(Intent.EXTRA_TEXT, tweetText);
			 startActivity(tweet);
		 }
		 return true;
	 }
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater(); 
		inflater.inflate(R.menu.options_menu, menu); 
		return true;
	}
 
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) 
		{
		case R.id.Refresh:
			loadFeed();
		break;
		case R.id.Start: 
	          if(!serviceFlag) setAlarm();
	    break;
		case R.id.Stop: 
	          if(serviceFlag) cancelAlarm();
	    break;
		case R.id.Saved:
			Intent savedArticlesIntent = new Intent(this, SavedArticles.class);
			startActivity(savedArticlesIntent);
		} 
		return true;
	}
	
	private void setAlarm(){
		serviceFlag = true;
	    Intent downloader = new Intent(this, AlarmReceiver.class);
	    PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
	    alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
	    alarms.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 60000, recurringDownload);
	    System.out.println("Setting alarm...");
	}
	
	private void cancelAlarm(){
		serviceFlag = false;
		Intent downloader = new Intent(this, AlarmReceiver.class);
	    PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
	    alarms.cancel(recurringDownload);
	}
	
	public void loadFeed(){
    	try{
	    	AndroidSaxFeedParser parser = new AndroidSaxFeedParser(feedURL);
	       	nprList = parser.parse();	    	
	    	Bundle extras = getIntent().getExtras();
	    	List<String> titles = extras.getStringArrayList("FeedList");
	    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.npr_item, titles);
	    	this.setListAdapter(adapter);
    	} catch (Throwable t){}
    }
}